from flask import Flask, request, jsonify
from flask_cors import CORS
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Create Flask application
app = Flask(__name__)

# Enable CORS for cross-origin requests
CORS(app)

# Configuration
app.config['JSON_AS_ASCII'] = False  # Support Chinese characters
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True

function_list = ["download_firmware", "upgrade_firmware", "gimbal_calibration", "other_functions"]

@app.route('/')
def home():
    return jsonify({
        'message': 'UAV Server is running,',
        'status': 'success',
        'version': 1.0
    })

@app.route('/api/functions')
def get_functions():
    """
    Returns a list of functions with their corresponding Python files.
    """
    import os
    current_dir = os.getcwd()
    
    # 为每个功能添加对应的py文件
    result = []
    for func in function_list:
        py_files = []
        for file in os.listdir(current_dir):
            if file.endswith('.py') and func.lower() in file.lower():
                py_files.append(file)
        result.append({
            'id': func,
            'py_files': py_files
        })
    
    return jsonify(result)

@app.route('/api/download_py/<function_name>')
def download_py_file(function_name):
    # 下载指定功能的py文件
    import os
    from flask import send_file
    
    if function_name not in function_list:
        return jsonify({"error": f"Function{function_name}' not found"}), 404  
    current_dir = os.getcwd()
    py_files = []
    
    # 查找匹配的py文件
    for file in os.listdir(current_dir):
        if file.endswith('.py') and function_name.lower() in file.lower():
            py_files.append(file)
    
    if not py_files:
        return jsonify({"error": f"Nopy files found for function {function_name}"}),404    
    # 返回第一个匹配的文件
    file_path = os.path.join(current_dir, py_files[0])
    return send_file(file_path, as_attachment=True, download_name=py_files[0])

# Error handlers
@app.errorhandler(404)
def not_found(error):
    return jsonify({
        'status': 'error',
        'message': 'Endpoint not found',
        'error': '404Not Found'
    }), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({
        'status': 'error',
        'message': 'Internal server error',
        'error': '50ernal Server Error'
    }), 500

if __name__ == '__main__':
    # Run in development mode
    app.run(
        host='0.0.0.0',  # Allow external access
        port=5000,     # Port number
        debug=True      # Debug mode
    ) 